package net.qiyuesuo;

import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import net.qiyuesuo.utils.HttpUtils;

/**
 *  以 HttpURLConnection 方式搭建的 客户端
 */
public class HttpClient { 
	
	private static Logger logger = LoggerFactory.getLogger(HttpClient.class);
	/**
	 * 向服务器发送 上传文件请求 /multipart
	 * @param filePath 文件路径 fileName 带后缀的文件名
	 * @return 返回服务器信息
	 */
	public static String sendUploadFileRequest(String filePath,String fileName) {
		String response = HttpUtils.upload("http://localhost:8080/file/upload", filePath, fileName);
		logger.info("服务器相应："+response);
		return response;
	}
	
	
	/**
	 * 向服务器发送 获取指定文件信息 请求
	 * 
	 * @param fileKey 文件uuid  
	 * @return 返回 服务器返回信息
	 */
	public static String sendGetInfoRquest(String fileKey) throws IOException{
		URL url =new URL("http://localhost:8080/file/getInfo?fileKey=" + fileKey);
		HttpURLConnection conn = (HttpURLConnection)url.openConnection();
		return HttpUtils.getResponse(conn,"GET");
	}
	
	/**
	 * 删除指定文件 
	 * @param fileKey
	 * @return 返回服务器信息
	 */
	public static String sendDeleteFileRequest(String fileKey) throws IOException{
		URL url =new URL("http://localhost:8080/file/delete?fileKey=" + fileKey);
		HttpURLConnection conn = (HttpURLConnection)url.openConnection();
		return HttpUtils.getResponse(conn,"POST");
	}
	
	/**
	 * 下载指定文件
	 * @param fileKey 文件uuid
	 * @return 返回byte类型数组
	 * @throws IOException
	 */
	public static byte[] sendDownloadFileRequest(String fileKey) throws IOException{
		URL url =new URL("http://localhost:8080/file/download?fileKey=" + fileKey);
		HttpURLConnection conn = (HttpURLConnection)url.openConnection();
		return HttpUtils.getResponse(conn,"GET").getBytes();
	} 
	
}
